package util

import (
	"fmt"
	"sync"
	"time"
)

const (
	MAXUINT32           = 99999
	DefaultUuidCntCache = 512
)

var instanceOfUUID *UUIDGenerator
var onceOfUUID sync.Once

type UUIDGenerator struct {
	Prefix       string
	idGen        uint32
	internalChan chan uint32
}

func GetTimeUUID() string {
	onceOfUUID.Do(func() {
		instanceOfUUID = NewUUIDGenerator("")
	})
	return time.Now().Format("200601021504") + instanceOfUUID.Get()
}

func NewUUIDGenerator(prefix string) *UUIDGenerator {
	fmt.Println("new....")
	gen := &UUIDGenerator{
		Prefix:       prefix,
		idGen:        0,
		internalChan: make(chan uint32, DefaultUuidCntCache),
	}
	gen.startGen()
	return gen
}

//开启 goroutine, 把生成的数字形式的UUID放入缓冲管道
func (this *UUIDGenerator) startGen() {
	go func() {
		for {
			if this.idGen == MAXUINT32 {
				this.idGen = 1
			} else {
				this.idGen += 1
				// fmt.Println(this.idGen)
			}
			this.internalChan <- this.idGen
		}
	}()
}

//获取带前缀的字符串形式的UUID
func (this *UUIDGenerator) Get() string {
	idgen := <-this.internalChan
	return fmt.Sprintf("%s%05d", this.Prefix, idgen)
}

//获取uint32形式的UUID
func (this *UUIDGenerator) GetUint32() uint32 {
	return <-this.internalChan
}

